package com.zhoug.common.http;


import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.ObservableSubscribeProxy;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.zhoug.common.content.Optional;
import com.zhoug.common.framework.eventbus.EventBusUtils;
import com.zhoug.common.framework.eventbus.EventMessage;
import com.zhoug.common.framework.rxjava2.SchedulerUtils;
import com.zhoug.common.http.core.BaseResponse;
import com.zhoug.common.http.core.ResponseTransformer;
import com.zhoug.common.http.core.RetrofitBuilder;
import com.zhoug.common.http.interceptors.TokenInterceptor;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.ReflectUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.lifecycle.LifecycleOwner;
import io.reactivex.Observable;
import retrofit2.Retrofit;

/**
 * 网络请求客服端基类
 * 泛型<T>:请求接口
 *
 * @Author HK-LJJ
 * @Date 2019/12/23
 * @Description
 */
public abstract class AbsHttpClient<T> {

    private static final String TAG = ">>>AbsHttpClient";
    private Retrofit retrofit;
    //服务器请求接口
    private T requestServer;
    private EventBusReceiver eventBusReceiver;//baseUrl改变后事件监听器
    public static final int CHANGE_SERVER=156;

    protected AbsHttpClient() {
        init();
    }



    /**
     * 初始化
     */
    @SuppressWarnings("unchecked")
    private void init(){
        retrofit = new RetrofitBuilder()
                .setDebug(getDebug())
                .addInterceptor(new TokenInterceptor())
                .build(getBaseUrl());

        Class<T> aClass = ReflectUtils.getGenericType(this.getClass(), 0);
        if (aClass != null) {
            LogUtils.d(TAG, "AbsHttpClient:aClass=" + aClass);
            requestServer = retrofit.create(aClass);
        }
        //注册监听
        eventBusReceiver=new EventBusReceiver();
        eventBusReceiver.registerEventBus();
    }

    /**
     * 释放资源
     * 重置BaseUrl
     */
    public void release() {
        retrofit = null;
        requestServer = null;
        if(eventBusReceiver!=null){
            eventBusReceiver.unregisterEventBus();
            eventBusReceiver=null;
        }
    }


    /**
     * BaseUrl
     *
     * @return
     */
    protected abstract String getBaseUrl() ;

    /**
     * debug
     *
     * @return
     */
    protected  boolean getDebug() {
        return false;
    }

    /**
     * 服务器请求接口
     * @return
     */
    public T getRequestMethods() {
        if(requestServer==null){
           synchronized (this){
               if(requestServer==null){
                   init();
               }
           }
        }
        return requestServer;
    }




    public static <T> ObservableSubscribeProxy<Optional<T>> handler(Observable<BaseResponse<T>> observable, LifecycleOwner lifecycleOwner) {
        return observable.compose(SchedulerUtils.apply())
                .compose(ResponseTransformer.handleResult())
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner)));

    }


    public static <T> Observable<Optional<T>> handler(Observable<BaseResponse<T>> observable) {
        return observable.compose(SchedulerUtils.apply())
                .compose(ResponseTransformer.handleResult());
    }

    public final class EventBusReceiver {

        private void registerEventBus(){
            EventBusUtils.register(this);
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onReceiver(EventMessage eventMessage) {
            if (eventMessage != null && eventMessage.getType() ==CHANGE_SERVER) {
                LogUtils.d(TAG, AbsHttpClient.this+">>>onReceiver: 服务器改变:"+eventMessage.getData());
                release();
            }
        }

        private void unregisterEventBus(){
            EventBusUtils.unregister(this);

        }
    }

}
